import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from "../views/Layout.vue"

Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    name: "Layout",
    component: Layout,
    children: [
      {
        path: "add",
        name: "add",
        component: () => import("../views/main/AddPaper"),
        meta: {
          isLogin: true
        }
      },
      {
        path: "download",
        name: "download",
        component: () => import("../views/main/GetPublickey"),
        meta: {
          isLogin: true
        }
      },
      {
        path: '',
        name: "query",
        component: () => import("../views/main/QueryInformation"),
        meta: {
          isLogin: true
        }
      },
      {
        path: "records",
        name: "records",
        component: () => import("../views/main/AccessRecord"),
        meta: {
          isLogin: true
        }
      },
    ]
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue")
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.isLogin)

  if (requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next({
        path: '/login',
      })
    } else {
      next()
    }
  } else {
    next()
  }
})